﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Options;
using Sgr.Identity;
using Sgr.Indentity.Utilities;

namespace Sgr.Indentity.Controllers
{
    /// <summary>
    /// 验证码服务接口
    /// </summary>
    [Route("api/v1/sgr/captcha")]
    [ApiController]
    [AllowAnonymous]
    [Produces("image/jpeg")]
    [Tags("Captcha")]
    public class CaptchaController : ControllerBase
    {
        private readonly CaptchaOptions _captchaOptions;

        /// <summary>
        /// 初始化验证码控制器
        /// </summary>
        /// <param name="captchaOptions">验证码配置选项</param>
        /// <exception cref="ArgumentNullException">当 captchaOptions 为空时抛出</exception>
        public CaptchaController(IOptions<CaptchaOptions> captchaOptions)
        {
            _captchaOptions = captchaOptions?.Value ?? throw new ArgumentNullException(nameof(captchaOptions));
        }

        /// <summary>
        /// 获取验证码图片
        /// </summary>
        /// <remarks>
        /// 获取一个验证码图片，根据配置可能是数字验证码或算术验证码。
        /// 验证码的哈希值将在响应头 'sgr-captcha' 中返回。
        /// </remarks>
        /// <returns>验证码图片（JPEG格式）</returns>
        /// <response code="200">成功获取验证码图片</response>
        /// <response code="429">请求过于频繁</response>
        [HttpGet]
        [EnableRateLimiting("RateLimiterPolicy.Sgr.Identity")]
        [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(FileContentResult))] // 明确返回类型
        [ProducesResponseType(StatusCodes.Status429TooManyRequests)]
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public ActionResult GetCaptcha()
        {
            try
            {
                (string code, byte[] image) = _captchaOptions.CaptchaIsArithmetic
                    ? ImageSharpCaptchaHelper.CreateArithmeticCaptcha()
                    : ImageSharpCaptchaHelper.CreateCaptcha();

                Response.Headers["sgr-captcha"] = ImageSharpCaptchaHelper.BuildCaptchaCode(code);
                return File(image, "image/jpeg");
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError);
            }
        }
    }
}